package com.atguigu.tingshu.search.service.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.thread.ThreadPoolConfig;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.BaseCategoryView;
import com.atguigu.tingshu.search.service.ItemService;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.atguigu.tingshu.vo.album.AlbumStatVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.*;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class ItemServiceImpl implements ItemService {

    /**
     * 查询专辑 详情
     *
     * @param albumId
     * @return
     */
    @Autowired
    private AlbumFeignClient albumFeignClient;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private ThreadPoolExecutor executor;

    @Override
    public Map<String, Object> albumInfo(Long albumId) {

        //线程安全map
        Map<String, Object> mapResult = new ConcurrentHashMap<>();
        //通过albumid获取专辑信息 统计信息 分类信息 主播信息 openfeign
        CompletableFuture<AlbumInfo> albumInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            AlbumInfo albumInfo = albumFeignClient.getAlbumInfo(albumId).getData();
            Assert.notNull(albumInfo, "专辑信息异常，专辑id{}", albumId);
            mapResult.put("albumInfo", albumInfo);
            return albumInfo;
        }, executor);

        //统计信息
        CompletableFuture<Void> albumStatCompletableFuture = CompletableFuture.runAsync(() -> {
            AlbumStatVo albumStatVo = albumFeignClient.getAlbumStatVo(albumId).getData();
            Assert.notNull(albumStatVo, "专辑统计信息异常，专辑id{}", albumId);
            mapResult.put("albumStatVo", albumStatVo);
        }, executor);

        //分类信息
        CompletableFuture<Void> baseCategoryViewCompletableFuture = albumInfoCompletableFuture.thenAcceptAsync((albumInfo) -> {
            Result<BaseCategoryView> categoryView = albumFeignClient.getCategoryView(albumInfo.getCategory3Id());
            BaseCategoryView baseCategoryView = categoryView.getData();
            mapResult.put("baseCategoryView", baseCategoryView);
        }, executor);
        //主播信息
        CompletableFuture<Void> announcerCompletableFuture = albumInfoCompletableFuture.thenAcceptAsync((albumInfo) -> {
            Result<UserInfoVo> userInfoVo = userFeignClient.getUserInfoVo(albumInfo.getUserId());
            mapResult.put("announcer", userInfoVo.getData());
        }, executor);

        CompletableFuture.allOf(albumInfoCompletableFuture,albumStatCompletableFuture,baseCategoryViewCompletableFuture,announcerCompletableFuture).join();


        return mapResult;
    }
}
